import 'dart:async';

import 'package:agora_rtc_engine/rtc_engine.dart';
import 'package:star_author/generated/json/base/json_convert_content.dart';
import 'package:star_author/provider/index.dart';
import 'package:star_author/utils/event.dart';
import 'package:star_author/utils/http/http_util.dart';
import 'package:star_author/utils/rong_im/rong_im.dart';
import 'package:star_author/utils/rouces_util.dart';
import 'package:star_author/views/stream/model/live_good_list_entity.dart';
import 'package:star_author/widgets/dialog/dialog_type.dart';
import 'package:star_author/widgets/dialog/sure_dialog.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:rongcloud_im_plugin/rongcloud_im_plugin.dart';

import '../../config/base_configuration.dart';
import '../../config/ui_constant.dart';
import '../../event_bus/global_event_bus.dart';
import '../../event_bus/rong_im_message_event.dart';
import '../../handler/common_permission_handler.dart';
import '../../utils/common_util/date_util.dart';
import '../../utils/common_util/toast/custom_toast.dart';
import '../../utils/utils.dart';
import 'dialog/good_list.dart';

class MuteMessageEvent {
  late Map message;

  MuteMessageEvent(this.message);
}

class StreamRtcBottom extends StatefulWidget {
  final TextEditingController controller;
  final FocusNode focusNode;
  final int anchorId;
  Function(bool isApply) applyCallBack;
  bool isClear;

  StreamRtcBottom({
    Key? key,
    required this.controller,
    required this.focusNode,
    required this.anchorId,
    required this.applyCallBack,
    this.isClear: false,
  }) : super(key: key);

  @override
  State<StreamRtcBottom> createState() => _StreamRtcBottomState();
}

class _StreamRtcBottomState extends State<StreamRtcBottom> {
  bool isBand = false;
  StreamSubscription<MuteMessageEvent>? _streamSubscriptionstream;
  Map et_user = {}; //被艾特人的信息
  String msg = "";
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Event.on('add_user_in_controller', (arg) {
      if ((arg ?? {}).isNotEmpty) {
        int index_where = widget.controller.text.indexOf("@");
        if (index_where == -1) {
          widget.controller.text += "@${arg['user_nickname'] ?? ""} ";
        } else {
          widget.controller.text = widget.controller.text.replaceAll(
              "@${et_user['user_nickname'] ?? ""} ",
              "@${arg['user_nickname'] ?? ""} ");
        }
        et_user = arg;
        isFocus = true;
        update(() {});
        widget.focusNode.requestFocus();
        moverCursor();
      }
    });
    Event.on("changed_interaction", (val) {
      if (!StreamConf.channelModel!.interaction) {
        update(() {
          isApply = false;
          widget.applyCallBack(isApply);
          isConnecting = false;
        });
      } else {
        update(() {});
      }
    });
    Event.on("getConnectCount", (arg) {
      if ((arg as VideoRemoteState) == VideoRemoteState.Stopped) {
        isApply = false;
        widget.applyCallBack(isApply);
        isConnecting = false;
        update(() {});
      }
      initConnectCount();
    });
    widget.focusNode.addListener(() {
      if (!widget.focusNode.hasFocus) {
        isFocus = false;
        update(() {});
      }
    });
    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
      init(false);
      getList();
      initConnectCount();
    });
  }

  UserProvider userProvider =
      Provider.of<UserProvider>(Get.context!, listen: false);
  int user_id = 0;

  getList() async {
    user_id = userProvider.user?['id'];
    HttpUtil.commonRequest(Get.context!,
            "/api/v1/studios/${StreamConf.liveId}/banned_user_list",
            queryParameters: {"user_id": user_id},
            isErrorToast: false,
            isCatchErrorLogin: false,
            isLoading: false)
        .then((value) {
      if (value.data['data'] == null || value.data['data'].length <= 0) {
        isBand = false;
        update(() {});
      } else {
        for (int i = 0; i < value.data['data'].length; i++) {
          if (value.data['data'][i]['id'].toString() == user_id.toString()) {
            if (DateUtil.getDateTime(value.data['data'][i]['time'])!
                    .difference(DateTime.now())
                    .inSeconds >
                0) {
              isBand = true;
            } else {
              isBand = false;
            }
          }
        }
        update(() {});
      }
    }).catchError((e) {});
  }

  init(bool isLoading) async {
    UserProvider userProvider =
        Provider.of<UserProvider>(Get.context!, listen: false);
    int user_id = userProvider.user?['id'];
    Event.on("localConnecting", (val) {
      update(() {
        isConnecting = true;
      });
    });
    Event.on("localCloseConnect", (val) {
      update(() {
        isApply = false;
        widget.applyCallBack(isApply);
        isConnecting = false;
      });
    });
    _streamSubscriptionstream =
        GlobalEventBus().bus.on<MuteMessageEvent>().listen((event) async {
      var message = event.message;
      if (message != null) {
        if (message['user_id'].toString() == user_id.toString()) {
          getList();
          initConnectCount();
        }
      }
    });
    initTimer();
  }

  Timer? timer;

  initTimer() {
    getBackfolws();
    timer = Timer.periodic(Duration(seconds: 30), (timer) {
      getBackfolws();
    });
  }

  getBackfolws() async {
    await HttpUtil.commonRequest(
      Get.context!,
      '/api/v1/studios/${StreamConf.liveId}/backflows',
      isLoading: false,
      isErrorToast: false,
      queryParameters: {
        "pre_page": 1,
      },
    ).then((value) {
      LiveGoodListEntity? listEntity =
          JsonConvert.fromJsonAsT<LiveGoodListEntity>(value.data);
      count = listEntity?.meta?.totalCount ?? 0;
      update(() {});
    });
  }

  update(VoidCallback fn) {
    if (mounted) {
      setState(fn);
    }
  }

  int count = 0;

  moverCursor() {
    widget.controller.selection = TextSelection.fromPosition(
        TextPosition(offset: widget.controller.text.length));
  }

  buildInputWidget(provider) {
    if (isBand) {
      return GestureDetector(
        child: Container(
          width: Get.width * 0.6,
          decoration: BoxDecoration(
            color: Color(0x4DFFFFFF),
            borderRadius: BorderRadius.circular(20.w),
          ),
          alignment: Alignment.centerLeft,
          padding: EdgeInsets.symmetric(
            horizontal: 14.w,
          ),
          child: Text(
            "您已被禁言，暂不可发弹幕",
            style: TextStyle(
              fontSize: 14.sp,
              color: UIConstant.color33,
            ),
          ),
          // height: 40.w,
          margin: EdgeInsets.only(
            right: 10.w,
          ),
          height: 40.w,
        ),
        onTap: () {
          CustomToast.show("您已被禁言，暂不可发弹幕");
        },
      );
    } else {
      return Container(
        width: Get.width * 0.6,
        decoration: BoxDecoration(
          color: Color(0x4D000000),
          borderRadius: BorderRadius.circular(20.w),
        ),
        padding: EdgeInsets.only(
          left: 14.w,
          right: 1.w,
        ),
        child: TextField(
          onSubmitted: (val) {
            sendMsg(val, provider);
          },
          onTap: () {
            isFocus = true;
            update(() {});
          },
          onChanged: (val) {
            //有艾特符号
            if (val.indexOf('@') != -1) {
              String nickname = "@${et_user['user_nickname']}";
              //删除消息内容
              if (val.endsWith(nickname)) {
                widget.controller.text = widget.controller.text
                    .replaceAll("@" + et_user['user_nickname'], "");
                et_user = {};
                moverCursor();
              } else {
                //添加消息内容
              }
            } else {
              //没有艾特符号
              et_user = {};
            }
            msg = val;
          },
          controller: widget.controller,
          focusNode: widget.focusNode,
          textInputAction: TextInputAction.done,
          decoration: InputDecoration(
            contentPadding: EdgeInsets.zero,
            suffixIcon: GestureDetector(
              child: Container(
                alignment: Alignment.centerRight,
                width: 40.w,
                height: 40.w,
                child: Image.asset(
                  RoucesUtil.getAssets('ic_live_send_lt'),
                  width: 40.w,
                  height: 40.w,
                ),
              ),
              onTap: () {
                if (isBand) {
                  CustomToast.show("您已被禁言，暂不可发弹幕");
                  return;
                }
                sendMsg(widget.controller.text, provider);
              },
            ),
            hintText: "点这里跟主播聊天",
            hintStyle: TextStyle(
              fontSize: 14.sp,
              color: UIConstant.color99,
            ),
            border: OutlineInputBorder(
              borderSide: BorderSide.none,
            ),
          ),
          style: TextStyle(
            fontSize: 14.sp,
            color: Colors.white,
          ),
        ),
        // height: 40.w,
        margin: EdgeInsets.only(
          right: 10.w,
        ),
        height: 40.w,
      );
    }
  }

  int ConnectCount = 0;

  bool isApply = false;

  initConnectCount() async {
    int user_id = userProvider.user?['id'] ?? 0;

    await HttpUtil.commonRequest(
      Get.context!,
      '/api/v1/studios/${StreamConf.liveId}/user_studios',
      isLoading: false,
      isErrorToast: false,
    ).then((value) {
      List data = value.data['data'] ?? [];
      data = data.reversed.toList();
      (data).forEach((element) {
        if (element['id'].toString() == user_id.toString()) {
          if (StreamConf.channelModel!.interaction) {
            isApply = true;
            widget.applyCallBack(isApply);
          }
        }
      });
      int indexWhere = (data).indexWhere(
          (element) => element['id'].toString() == user_id.toString());
      if (indexWhere == -1) {
        ConnectCount = data.length;
        isApply = false;
      } else {
        isApply = true;
        ConnectCount = indexWhere;
      }
      update(() {});
    });
  }

  getColor() {
    Color button_color = rgba(190, 190, 190, 1);

    if (isBand) {
      button_color = rgba(190, 190, 190, 1);
    } else if (StreamConf.channelModel!.interaction) {
      button_color = rgba(68, 169, 73, 1);
    }
    return button_color;
  }

  bool isConnecting = false;

  @override
  void didUpdateWidget(covariant StreamRtcBottom oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
    if (oldWidget.isClear != widget.isClear) {
      update(() {});
    }
  }

  bool isFocus = false;

  @override
  Widget build(BuildContext context) {
    if (widget.isClear) return Container();
    return Consumer<UserProvider>(
      builder: (context, provider, child) {
        return Container(
          margin: EdgeInsets.only(
            left: 12.w,
            top: 12.w,
            bottom: MediaQuery.of(context).padding.bottom + 12.w,
          ),
          child: Row(
            children: [
              Expanded(
                child: buildInputWidget(provider),
              ),
              if (!isFocus)
                Builder(builder: (context) {
                  if (isConnecting) {
                    //ic_user_connecting
                    return GestureDetector(
                      child: Container(
                        height: 40.w,
                        width: 80.w,
                        decoration: BoxDecoration(
                          color: rgba(68, 169, 73, 1),
                          borderRadius: BorderRadius.circular(20.w),
                        ),
                        alignment: Alignment.center,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Container(
                              child: Stack(
                                alignment: Alignment.center,
                                children: [
                                  RoucesUtil.getAssetsIcon(
                                    'ic_user_connecting_lt',
                                    22.w,
                                  ),
                                  Positioned(
                                    child: Image.asset(
                                      'images/video_loading_lt.gif',
                                      width: 10.w,
                                      height: 12.w,
                                      color: Colors.white,
                                    ),
                                    bottom: 0,
                                  )
                                ],
                              ),
                            ),
                            SizedBox(
                              width: 2.w,
                            ),
                            Text(
                              '连麦中',
                              style: TextStyle(
                                fontSize: 12.sp,
                                color: Colors.white,
                              ),
                            ),
                          ],
                        ),
                        margin: EdgeInsets.only(
                          right: 10.w,
                        ),
                      ),
                      onTap: () {
                        DialogUtil.showMyDialog(
                            dialogType: DialogType.Disconnect,
                            rightButtonOnTap: () {
                              setState(() {
                                isConnecting = false;
                                isApply = false;
                                widget.applyCallBack(isApply);
                              });
                              Event.emit("close_connecting_settings");
                            });
                      },
                    );
                  } else {
                    if (isBand) {
                      return GestureDetector(
                        child: Container(
                          child: buildConnectButton(),
                          margin: EdgeInsets.only(
                            right: 10.w,
                          ),
                        ),
                        onTap: () {
                          if (isBand) {
                            DialogUtil.showMyDialog(
                                dialogType:
                                    DialogType.banned_cant_connect_microphone);
                          }
                        },
                      );
                    } else if (isApply) {
                      return GestureDetector(
                        child: Container(
                          alignment: Alignment.center,
                          height: 40.w,
                          width: 80.w,
                          decoration: BoxDecoration(
                            color: rgba(68, 169, 73, 1),
                            borderRadius: BorderRadius.circular(20.w),
                          ),
                          //ic_live_can_connect
                          //ic_live_connecting
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Text(
                                '$ConnectCount',
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  color: Colors.white,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                              Text(
                                '连麦排队',
                                style: TextStyle(
                                  fontSize: 10.sp,
                                  color: Colors.white,
                                ),
                              ),
                            ],
                          ),
                          margin: EdgeInsets.only(
                            right: 10.w,
                          ),
                        ),
                        onTap: () async {
                          await initConnectCount();
                          DialogUtil.showMyDialog(
                            dialogType: DialogType.exit_queue_microphone,
                            param: {
                              "count": ConnectCount,
                            },
                            leftButtonOnTap: () {},
                            rightButtonOnTap: () async {
                              await HttpUtil.commonRequest(
                                Get.context!,
                                '/api/v1/studios/${StreamConf.liveId}/leave_user_studios',
                                method: HttpUtil.MethodPost,
                              ).then((value) {
                                RongUtil.operation(
                                    OperationKey.user_to_connect, {});
                                setState(() {
                                  isApply = false;
                                  widget.applyCallBack(isApply);
                                });
                              });
                            },
                          );
                        },
                      );
                    } else {
                      return GestureDetector(
                        child: buildConnectButton(),
                        onTap: () {
                          if (isBand) {
                            DialogUtil.showMyDialog(
                                dialogType:
                                    DialogType.banned_cant_connect_microphone);
                            return;
                          }
                          if (!StreamConf.channelModel!.interaction) {
                            DialogUtil.showMyDialog(
                              dialogType: DialogType.cant_connect_microphone,
                            );
                            return;
                          }
                          checkPermission();
                        },
                      );
                    }
                  }
                }),
              if (!isFocus)
                GestureDetector(
                  child: Container(
                    height: 40.w,
                    width: 40.w,
                    alignment: Alignment.center,
                    child: Stack(
                      clipBehavior: Clip.none,
                      children: [
                        Image.asset(
                          RoucesUtil.getAssets('bg_wait_bidder_list_lt'),
                          width: 40.w,
                          height: 40.w,
                          fit: BoxFit.cover,
                        ),
                        Container(
                          alignment: Alignment.bottomCenter,
                          margin: EdgeInsets.only(bottom: 4.w),
                          child: Text(
                            '$count',
                            style: TextStyle(
                                fontSize: 10.sp,
                                color: Colors.white,
                                fontWeight: FontWeight.w500),
                          ),
                        ),
                      ],
                    ),
                    margin: EdgeInsets.only(
                      right: 20.w,
                    ),
                  ),
                  onTap: () async {
                    showModalBottomSheet(
                      builder: (BuildContext context) {
                        //构建弹框中的内容
                        return GoodList(
                          totalCount: count,
                        );
                      },
                      backgroundColor: Colors.transparent, //重要
                      isScrollControlled: true,
                      context: context,
                    );
                  },
                ),
            ],
          ),
        );
      },
    );
  }

  buildConnectButton() {
    return Container(
      width: 80.w,
      height: 40.w,
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          Container(
            width: 80.w,
            height: 40.w,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: getColor(),
              borderRadius: BorderRadius.circular(20.w),
            ),
            child: Text(
              "申请鉴宝",
              style: TextStyle(
                fontSize: 14.sp,
                color: Colors.white,
              ),
            ),
            margin: EdgeInsets.only(
              right: 10.w,
            ),
          ),
        ],
      ),
    );
  }

  Future _initPermission() {
    return [Permission.camera, Permission.microphone, Permission.storage]
        .request();
  }

  checkPermission() async {
    Map<Permission, PermissionStatus> map = await _initPermission();
    //全部同意 可以连麦
    if (map[Permission.camera] == PermissionStatus.granted &&
        map[Permission.microphone] == PermissionStatus.granted &&
        map[Permission.storage] == PermissionStatus.granted) {
      await initConnectCount();
      //去链接
      DialogUtil.showMyDialog(
        dialogType: DialogType.apply_connect_microphone,
        param: {
          "count": ConnectCount,
        },
        leftButtonOnTap: () {},
        rightButtonOnTap: () async {
          await HttpUtil.commonRequest(
            Get.context!,
            '/api/v1/studios/${StreamConf.liveId}/apply_user_studios',
            method: HttpUtil.MethodPost,
          ).then((value) {
            RongUtil.operation(OperationKey.user_to_connect, {});
            initConnectCount();
          });
        },
      );
    } else {
      List status = [
        PermissionStatus.permanentlyDenied,
        PermissionStatus.denied
      ];
      if (status.contains(map[Permission.camera])) {
        //相机权限拒绝
        CommonPermissionHandler.showTipDialog(context,
            content: CommonPermissionHandler.cameraRequestPermissionTip);
      } else if (status.contains(map[Permission.microphone])) {
        CommonPermissionHandler.showTipDialog(context,
            content: CommonPermissionHandler.microphoneRequestPermissionTip);
      } else if (status.contains(map[Permission.storage])) {
        CommonPermissionHandler.showTipDialog(context,
            content: CommonPermissionHandler.storageRequestPermissionTip);
      }
    }
  }

  //发送消息
  sendMsg(String val, UserProvider userProvider) async {
    if (val.trim().length == 0) {
      CustomToast.show('请输入消息后发送');
      return;
    }
    String text = val.trim();
    FocusScope.of(context).unfocus(); //失去焦点
    widget.controller.clear();
    try {
      Message? msg = await RongUtil.sendMsg(text, userProvider, param: et_user);
      RongIMClient.onMessageSend =
          (int? messageId, int? status, int? code) async {
        if (status == RCSentStatus.Sent) {
          if (msg != null) {
            Message? message = await RongIMClient.getMessage(msg.messageId!);
            GlobalEventBus().bus.fire(RongIMMessageEvent(message!));
          }
        } else if (status == RCSentStatus.Failed) {
          if (code == 23408) {
            CustomToast.show('您已被禁言');
          } else {
            CustomToast.show('发送消息失败');
          }
        }
      };
      // await API.sendWords(StreamConf.liveId, text);
    } catch (e) {
      DioError dioError = e as DioError;
      CustomToast.show(dioError.message);
    }
  }

  @override
  void dispose() {
    super.dispose();
    _streamSubscriptionstream?.cancel();
    Event.off(
      "localConnecting",
    );
    timer?.cancel();
    Event.off("changed_interaction");
    Event.off("add_user_in_controller");
    Event.off("getConnectCount");
    Event.off("localCloseConnect");
  }
}
